package cn.Y_Qiu.org.service.impl;

import cn.Y_Qiu.basic.service.impl.BaseServiceImpl;
import cn.Y_Qiu.basic.util.StrUtils;
import cn.Y_Qiu.org.domain.Employee;
import cn.Y_Qiu.org.mapper.EmployeeMapper;
import cn.Y_Qiu.org.service.IEmployeeService;
import cn.Y_Qiu.user.domain.LoginInfo;
import cn.Y_Qiu.user.mapper.LoginInfoMapper;
import cn.Y_Qiu.user.util.MD5Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LoginInfoMapper loginInfoMapper;


    /**
     *  重写添加方法，需要在logininfo表中添加employee登录用信息
     * @param employee 员工管理前端传入的员工信息
     */
    @Transactional
    @Override
    public void add(Employee employee) {
        initEmpolyee(employee);
        LoginInfo info =  employee2Logininfo(employee);
        loginInfoMapper.add(info);
        employee.setLogininfo_id(info.getId());
        employeeMapper.add(employee);
    }

    @Transactional
    @Override
    /**
     *  重写删除方法，需要级联删除logininfo表中的关联信息
     */
    public void remove(Long id) {
        loginInfoMapper.remove(employeeMapper.queryById(id).getLogininfo_id());
        employeeMapper.remove(id);

    }

    /**
     *
     * employee信息复制到logininfo
     *
     * @return
     */
    private LoginInfo employee2Logininfo(Employee employee) {
        LoginInfo info = new LoginInfo();
        BeanUtils.copyProperties(employee, info);
        info.setType(0);
        return info;
    }

    /**
     *   * @param employee
     * @param employee
     */
    private void initEmpolyee(Employee employee) {
        String salt = StrUtils.getRandomString(32);
        String password = MD5Utils.encrypByMd5(salt + employee.getPassword());
        employee.setSalt(salt);
        employee.setPassword(password);
    }


}
